﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using HC.XAP.FileUpload.Module.BusinessObjects.FileUpload;
using HC.XAP.FileSystemData.BusinessObjects;

namespace HC.XAP.FileUpload.Module.Controllers
{
    // For more typical usage scenarios, be sure to check out https://documentation.devexpress.com/eXpressAppFramework/clsDevExpressExpressAppViewControllertopic.aspx.
    public partial class UploadInPopupController : ViewController<ListView>
    {
        public UploadInPopupController()
        {
            TargetObjectType = typeof(HCOBFileUpload);
            var customUploadFileAction = new PopupWindowShowAction(this, "CustomUploadFileAction", PredefinedCategory.View)
            {
                Caption = "上传文件",
                ImageName = "AddFile",
                TargetViewType = ViewType.ListView
                
            };
            customUploadFileAction.Execute += CustomUploadFileAction_Execute;
            customUploadFileAction.CustomizePopupWindowParams += CustomUploadFileAction_CustomizePopupWindowParams;
        }
        private void CustomUploadFileAction_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
        {
            var upFileParameter = e.PopupWindowViewCurrentObject as UploadFileParameters;
            var fileInfos = upFileParameter.FileStreams;//获取上传的文件
            if (fileInfos == null || fileInfos.Count <= 0)
            {
                Application.ShowViewStrategy.ShowMessage("未上传任何文件,请先上传.", InformationType.Error, 5000, InformationPosition.Top);
                e.CanCloseWindow = false;
                return;
            }
            foreach (var upFile in fileInfos)
            {
                var newFile = ObjectSpace.CreateObject<HCOBFileUpload>();
                FileSystemStoreObject fileCopy = ObjectSpace.CreateObject<FileSystemStoreObject>();
                fileCopy.FileName = upFile.FileName;
                var s = new MemoryStream(upFile.FileStream.ToArray());
                fileCopy.TempSourceStream = s;
                newFile.SystemStoreFile = fileCopy;//保存文件
                newFile.UpLoadDate = DateTime.Now;
            }
            ObjectSpace.CommitChanges();
            ObjectSpace.Refresh();
            this.View.Refresh();

           
        }
        private void CustomUploadFileAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            NonPersistentObjectSpace os = (NonPersistentObjectSpace)e.Application.CreateObjectSpace(typeof(UploadFileParameters));
            os.PopulateAdditionalObjectSpaces(Application);
            e.DialogController.SaveOnAccept = false;
            e.View = e.Application.CreateDetailView(os, os.CreateObject<UploadFileParameters>());
        }

    }
}
